package Dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import Entity.Room_user;
import Entity.User;
import tool.HibernateSessionFactory;

public class DAORoom_user extends DAOAbstract{
	
	public boolean addRoomUser(Room_user rm){
		Session session = HibernateSessionFactory.getSession();
		session.clear();
		try {
			session.beginTransaction();
			session.save(rm);
			session.getTransaction().commit();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
			return false;
		}
	}
	
	public Map<String, Object> queryUserByRoomid(int roomid){
		Session session = HibernateSessionFactory.getSession();
		session.clear();
		try {
			session.beginTransaction();
			Query query = session.createQuery("from Room_user where roomid = ? and status = 1").setInteger(0, roomid);
			List<Room_user> list = query.list();
			Query query2 = session.createQuery("from User where idcard = ? and status = 1").setString(0, list.get(0).getIdcard());
			List<User> list2 = query2.list();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", list2.get(0).getName());
			map.put("idcard", list2.get(0).getIdcard());
			map.put("roomid", roomid);
			map.put("starttime", list.get(0).getStarttime());
			session.getTransaction().commit();
			System.out.println(map);
			return map;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	
	
	public int checkOut(int roomid, String leavetime){
		Session session = HibernateSessionFactory .getSession();
		session.clear();
		try {
			session.beginTransaction();
			Query query = session.createQuery("from Room_user where roomid = ? and status = 1").setInteger(0, roomid);
			List<Room_user> list = query.list();
			Room_user roomUser = list.get(0);
			roomUser.setStatus(2);
			roomUser.setLeavetime(leavetime);
			session.update(roomUser);
			session.getTransaction().commit();
			System.out.println(roomUser.getDay());
			return roomUser.getDay();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			session.getTransaction().rollback();
			return -1;
		}
	}
}